package ar.uba.fi.tonyvaliente.documents;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import ar.uba.fi.tonyvaliente.files.Persistor;
import ar.uba.fi.tonyvaliente.files.PersistorException;

public class DocumentInfoPersistor extends Persistor<DocumentInfo> {
	@Override
	public DocumentInfo deserialize(byte[] bytes) throws PersistorException {
		ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
		DataInputStream in = new DataInputStream(bais);

		try {
			byte hashLengthByte = in.readByte();
			int hashLength = (int) hashLengthByte;
			byte[] hashBytes = new byte[hashLength];
			in.read(hashBytes);
			String hash = new String(hashBytes);

			byte titleLengthByte = in.readByte();
			int titleLength = (int) titleLengthByte;
			byte[] titleBytes = new byte[titleLength];
			in.read(titleBytes);
			String title = new String(titleBytes);

			return new DocumentInfo(hash, title);
		} catch (IOException e) {
			e.printStackTrace();
			throw new PersistorException("Error deserializando DocumentInfo", e);
		}
	}

	@Override
	public byte[] serialize(DocumentInfo t) throws PersistorException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream out = new DataOutputStream(baos);

		try {
			out.writeByte(t.getHash().length());
			out.writeBytes(t.getHash());

			out.writeByte(t.getTitle().length());
			out.writeBytes(t.getTitle());
		} catch (IOException e) {
			e.printStackTrace();
			throw new PersistorException("Error serializando DocumentInfo", e);
		}

		return baos.toByteArray();
	}
}
